# This controller handles the login/logout function of the site.  
class SessionsController < ApplicationController
  # Be sure to include AuthenticationSystem in Application Controller instead
  include AuthenticatedSystem
  # If you want "remember me" functionality, add this before_filter to Application Controller
  before_filter :login_from_cookie

  # render new.rhtml
  def new
    @page_title = "Connexion"
    @room_id = request.parameters['room_id']
    respond_to do |format|
      format.html
      format.js {render :action => 'new.rjs', :locals => {:room_id => @room_id}}
    end
  end

  def create
    if request.xhr?
      @room_id = params[:room_id]
      @see = 'stat'
      @room_view = Room.find(@room_id)
      @rooms = Room.find :all
      @incidents = Incident.find :all, :conditions => [ 'resolved_at IS NULL' ]
    end
    self.current_user = User.authenticate(params[:login], params[:password])
    if logged_in?
      if params[:remember_me] == "1"
        self.current_user.remember_me
        cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
      end
      flash[:notice] = "Connection réussi"
      respond_to do |format|
        format.html { redirect_to '/'}
        format.js
      end
    else
      flash[:notice] = "Votre login ou mot de passe est éronné"
      respond_to do |format|
        format.html { render :action => 'new' }
        format.js { render :action => 'error_create.rjs' }
      end
    end
  end

  def destroy
    self.current_user.forget_me if logged_in?
    cookies.delete :auth_token
    reset_session
    flash[:notice] = "Déconnection effectuée"
    redirect_back_or_default('/')
  end
end
